import { ConfigEnv, defineConfig,loadEnv,normalizePath, UserConfigExport } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import autoprefixer from "autoprefixer"
import path from 'path';
import ElementPlus from 'unplugin-element-plus/vite';
import { viteMockServe } from 'vite-plugin-mock'
const pathSrc = path.resolve(__dirname, 'src')
// https://vitejs.dev/config/
export default ({mode,command }:ConfigEnv):UserConfigExport=>{
  const {VITE_APP_MOCK,VITE_APP_BASE_API,VITE_APP_BASE_URL} = loadEnv(mode, process.cwd())
  return defineConfig({
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
      extensions: ['.ts', '.js', '.vue', '.json', '.d.ts', '.tsx']
    },
    css:{
      preprocessorOptions:{
        scss:{
          additionalData:`@use "@/assets/scss/elementPlus/index.scss" as *;` //引入scss文件
        }
      },
      postcss: {
        plugins:[
          autoprefixer({
            overrideBrowserslist:['Chrome>40',"ff > 31","ie >= 8","iOS 7.1"]
          })
        ]
      }
    },
    plugins: [
      vue(),
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve' && VITE_APP_MOCK === 'true', // 开发打包开关
        prodEnabled: command !== 'serve', // 生产打包开关
        logger: true
      }),
      AutoImport({
        // Auto import functions from Vue, e.g. ref, reactive, toRef...
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: ['vue'],
        // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)
        // 自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式)
        resolvers: [
          ElementPlusResolver(),
          // Auto import icon components
          // 自动导入图标组件
          IconsResolver({
            prefix: 'Icon',
          }),
        ],
        dts: path.resolve('./typings/plugins', 'auto-imports.d.ts'),
      }),
      // 按需引入样式scss
      ElementPlus({
        useSource: true,
      }),
  
      Components({
        resolvers: [
          // Auto register icon components
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),
          // Auto register Element Plus components
          // 自动导入 Element Plus 组件
          ElementPlusResolver({ importStyle: "sass" }),
        ],
  
        dts: path.resolve('./typings/plugins', 'components.d.ts'),
      }),
  
      Icons({
        autoInstall: true,
      }),
    ],
    server: {
      port: 8080,
      proxy: {
        [`/${VITE_APP_BASE_API}`]: {
          target: VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: path => path.replace(VITE_APP_BASE_API, '')
        }
      },
      hmr: true
    },
    
    build: {
      sourcemap: mode === 'dev',
      // 大文件报警阈值设置,不建议使用
      chunkSizeWarningLimit: 5000,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      rollupOptions: {
        output: {
          manualChunks (id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          },
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
        }
      }
    },
  })
}
